from django.http import JsonResponse
from .models import Users,CustomToken
# Create your views here.
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
import json
from utils.serializers import LoginSerializer
from django.views.decorators.csrf import csrf_exempt
from utils.crypto import DECRYPT
from datetime import datetime, timedelta
from utils.decorators import token_required
import requests
import socket


def send_udp_command(esp32_ip, port, cmd):
    # 创建 UDP 套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        message = cmd.encode('utf-8')  # 转为字节流
        udp_socket.sendto(message, (esp32_ip, port))
        print(f"已向 {esp32_ip}:{port} 发送 UDP 指令：{cmd}")
    except Exception as e:
        print(f"UDP 发送失败：{str(e)}")
    finally:
        udp_socket.close()  # 关闭套接字

@token_required
@csrf_exempt
def index(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    light = data.get('light')
    esp32_ip = "192.168.3.77"  # 替换为 ESP32 的实际 IP
    # esp32_ip = "192.168.1.2"  # 替换为 ESP32 的实际 IP
    # send_udp_command(esp32_ip,8080,light)
    send_udp_command(esp32_ip,7788,light)
    return HttpResponse("Hello, world. You're at the polls index.")

@csrf_exempt
def users_register(request):
    if request.method == 'POST':
        try:
            res = json.loads(request.body.decode('utf-8'))['secret']
            data = json.loads(DECRYPT.decrypt(res))
            username = data.get('username')
            email = data.get('email')
            password_hash = make_password(data.get('password'))
            if Users.objects.filter(email=email).exists():
                secret = DECRYPT.encrypt({'status': 'error', 'message': '邮箱已经被注册','code':200})
                return JsonResponse({'secret': secret}, status=200)
            # 业务逻辑：创建用户
            user = Users.objects.create(username=username, email=email,password_hash=password_hash)
            secret = DECRYPT.encrypt({'status': 'success', 'message': '账号创建成功','code':200})
            return JsonResponse({'secret':secret}, status=200)
        except Exception as e:
            secret = DECRYPT.encrypt({'status': 'error', 'message': str(e)})
            return JsonResponse({'secret':secret}, status=400)
    secret = DECRYPT.encrypt({'status': 'error', 'message': 'Method not allowed'})
    return JsonResponse({'secret':secret}, status=405)


@csrf_exempt
def users_sign(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))['secret']
        serializer = LoginSerializer(data=json.loads(DECRYPT.decrypt(data)))
        if serializer.is_valid():
            email = serializer.data.get('email')
            user = Users.objects.get(email=email)
            token, created = CustomToken.objects.get_or_create(user=user)
            print(str(token),'token')
            # 可根据需要更新过期时间等
            token.expired_at = datetime.now() + timedelta(hours=24)
            token.save()
            secret = DECRYPT.encrypt({'status': 'success','data':{
                'username': user.username,
                'email': user.email,
            }, 'message': '登录成功','code':200,'token':str(token)})
            return JsonResponse({'secret': secret},status=200)
        else:
            secret = DECRYPT.encrypt({'status': 'error', 'message': serializer.errors['non_field_errors'][0],'code':401})
            return JsonResponse({'secret':secret},status=200)
    secret = DECRYPT.encrypt({'status': 'error', 'message': 'Method not allowed'})
    return JsonResponse({'secret': secret},status=200)
